package com.bsdsma.fengheguaiapp.service.impl;

import com.bsdsma.fengheguaiapp.constants.ErrorCodes;
import com.bsdsma.fengheguaiapp.cos.CosUploadDTO;
import com.bsdsma.fengheguaiapp.cos.CosUtils;
import com.bsdsma.fengheguaiapp.exceptionhandler.GlobalRuntimeException;
import com.bsdsma.fengheguaiapp.service.FileService;
import com.bsdsma.fengheguaiapp.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Autowired
    private CosUtils cosUtils;

    /**
     * 获取文件后缀
     * eg: xxx.jpg -> jpg
     * @param filename  文件名
     */
    private String getSuffix(String filename){
        return filename.substring(filename.lastIndexOf(".") + 1);
    }

    @Override
    public CosUploadDTO upload(MultipartFile multipartFile) {
        String originalFilename = multipartFile.getOriginalFilename();
        if(StringUtils.isBlank(originalFilename)){
            throw new GlobalRuntimeException(ErrorCodes.FILE_UPLOAD_ERROR, "源文件名为空");
        }
        String suffix = this.getSuffix(originalFilename);
        log.info("original filename -> {}", originalFilename);
        String newFilename = UUID.randomUUID().toString().replace("-", "") + "." + suffix;
        String key = "/fengheguaiapp/" + newFilename;
        File file;
        try {
            file = File.createTempFile(originalFilename, suffix);
            multipartFile.transferTo(file);
        } catch (IOException e) {
            throw new GlobalRuntimeException(ErrorCodes.FILE_UPLOAD_ERROR, "文件转换失败");
        }
        return cosUtils.upload(key, file);
    }
}
